import React, { useEffect, useRef, useState } from 'react'
import {
  Slider,
  colors,
} from '@material-ui/core';
import { Icon } from 'components/atoms';
import { useSelector } from 'react-redux';

import 'assets/css/rootPlay.css';
import audioImg from 'assets/images/audioImg.png'
import audioMp3 from 'assets/audio/audioMp3.mp3';


export default function MusicPlay({ musicInfoList }) {

  const openPlaylist = useSelector((state) => state.playlist.openPlaylist)

  const musicRef = useRef()
  const [musicInfo, setMusicInfo] = useState([])
  const [musicIndex, setMusicIndex] = useState(0)
  const [musicSrc, setMusicSrc] = useState(audioMp3)
  const [musicImg, setMusicImg] = useState(audioImg)
  const [musicName, setMusicName] = useState("Turn The Party Out (Single)")
  const [musicArt, setMusicArt] = useState("Silky Redd")
  const [currentTime, setCurrentTime] = useState(0)
  const [maxTime, setMaxTime] = useState('')
  const [musicVolume, setMusicVolume] = useState('')
  const [musicTimer, setMusicTimer] = useState('')
  const [musicPlay, setMusicPlay] = useState(false)

  useEffect(() => {
    setMusicIndex(0)
    setMusicInfo([...musicInfoList])
  }, [musicInfoList])

  useEffect(() => {
    if (musicInfoList.length) {
      if (musicInfo.length === 0) return setMusicInfo([...musicInfoList])
      setMusicImg(audioImg)
      // setMusicName(musicInfo[musicIndex].albumName)
      // setMusicArt(musicInfo[musicIndex].artistName)
      // setMusicSrc(musicInfo[musicIndex].remotePath)
    }
  }, [musicInfo, musicInfoList])


  useEffect(() => {
    if (musicInfo.length == 0) return

    // const { musicName, musicArt, musicSrc } = musicInfo[musicIndex]
    // setMusicName(musicInfo[musicIndex].albumName)
    // setMusicArt(musicInfo[musicIndex].artistName)
    // setMusicSrc(musicInfo[musicIndex].remotePath)
    // setTimeout(playMusic, 500)

  }, [musicIndex, musicInfoList])

  const songTimeFilter = (val) => {
    const dt = new Date(val * 1000)
    const mm = (dt.getMinutes() + '').padStart(2, '0')
    const ss = (dt.getSeconds() + '').padStart(2, '0')
    return `${mm}:${ss}`
  }

  const playMusic = () => {
    if (musicSrc) {
      if (musicRef.current.paused) {
        if (!musicVolume) {
          musicRef.current.volume = 0.1
          setMusicVolume(0.1)
        }
        if (musicRef.current.error == null) {
          console.log(musicRef, "5555")
          musicRef.current.play()
        }
        watchMusicInfo()
        setMusicPlay(true)
      } else {
        musicRef.current.pause()
        setMusicPlay(false)
        clearInterval(musicTimer)
      }
    }
  }

  const watchMusicInfo = () => {
    clearInterval(musicTimer)
    setMaxTime(musicRef.current.duration)

    const theTimer = setInterval(() => {
      setMusicTimer(theTimer)

      if (musicRef.current) {
        if (musicRef.current.paused) {
          clearInterval(musicTimer)
          setMusicPlay(false)
        }

        if (musicRef.current.ended) {
          clearInterval(musicTimer)
          //  setMusicPlay(false)
          changeMusicTime('', 0)
        }
        setCurrentTime(musicRef.current.currentTime)

      }
    }, 500)
  }

  const changeMusicTime = (event, newValue) => {
    setCurrentTime(newValue)
    clearInterval(musicTimer)
    musicRef.current.currentTime = newValue

    if (musicRef.current.paused) musicRef.current.play()
    setMusicPlay(true)

    watchMusicInfo()
  }

  const setVolume = (val) => {
    if (!musicVolume) {
      musicRef.current.volume = 0.1
      setMusicVolume(0.1)
      return
    }
    if (!val) return
    musicRef.current.volume = val
  }
  const changePlayerVolume = (e, value) => {
    if (value == 0) return (musicRef.current.volume = 0)
    setMusicVolume(value / 10)
    setVolume(value / 10)
  }

  const formatter = (value) => songTimeFilter(value)

  const changePlayMusic = (num) => {
    const index = musicIndex + num
    if (index < 0) return setMusicIndex(musicInfo.length - 1)
    if (index >= musicInfo.length) return setMusicIndex(0)

    setMusicIndex(index)
  }

  const [activePlay, setActivePlay] = useState(0)
  const [showVolume, setShowVolume] = useState(false)

  const volumeClick = () => {
    setShowVolume(!showVolume)
  }

  return (
    <>
      <div className='rootPlay'>

        <div className="rootBox">

          <div className="rootImage">
            <img src={musicImg} alt='' width={"100%"} height={"100%"} style={{ objectFit: "cover" }} />
          </div>

          <div className="rootInfo">

            <div className="rootProgressBar">
              <Slider
                tooltip={{ formatter }}
                value={currentTime}
                max={maxTime ? maxTime : 0}
                onChange={changeMusicTime}
              />
            </div>
            <div className="rootProfile">
              <div>{musicName}</div>
              <div>{musicArt}</div>
            </div>
            <div className="rootTime">
              {songTimeFilter(currentTime)} / {songTimeFilter(maxTime)}
            </div>

          </div>

          <div className='rootMain'>
            <audio ref={musicRef} type="audio" src={musicSrc}></audio>
            <div className="operationBar">
              <Icon
                fontIconClass="fas fa-step-backward"
                fontIconColor={"#fff"}
                onClick={() => changePlayMusic(-1)}
              />
              {musicPlay ? (
                <Icon
                  fontIconClass="fas fa-pause"
                  fontIconColor={"#fff"}
                  onClick={playMusic}
                  className="marginIcon"
                />
              ) : (
                <Icon
                  fontIconClass="fa fa-play"
                  fontIconColor={"#fff"}
                  onClick={playMusic}
                  className="marginIcon"
                />
              )}
              <Icon
                fontIconClass="fas fa-step-forward"
                fontIconColor={"#fff"}
                onClick={() => changePlayMusic(1)}
              />
            </div>
          </div>
          <div className="rootvolume_icon">
            <Icon
              className="icon"
              fontIconClass="fas fa-volume-down"
              fontIconColor={"#fff"}
              size='medium'
            />

            <Icon
              className="icon_mobile"
              fontIconClass="fas fa-volume-down"
              fontIconColor={"#fff"}
              onClick={volumeClick}
              size='medium'
            />

            <div className="volumeSlider_mobile" style={{ display: showVolume ? "block" : "none" }}>
              <Slider defaultValue={0} max={10} onChange={changePlayerVolume} orientation="vertical" />
            </div>
          </div>

          <div className="volumeSlider">
            <Slider defaultValue={0} max={10} onChange={changePlayerVolume} />
          </div>


        </div>
      </div>

    </>

  )
}